﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Game_Engine
{
    public class SphereCollider : Collider
    {
        public float Radius
        {
            get;
            set;
        }

        public SphereCollider()
        {
            Name = "SphereCollider";
            Radius = 1;
        }

        public override bool Collides(Collider collider, out Vector3 normal)
        {
            if (collider is SphereCollider)                                                      //We confirm that our local variable is of the correct type
            {                                                                                   //and then change that local variable to the same type in order
                SphereCollider sc = collider as SphereCollider;
                Vector3 span = Transform.Position - sc.Transform.Position;                      //to access the necessary properties of the other collider
                if (span.Equals(Vector3.Zero))
                {
                    normal = Vector3.Zero;
                    return false;
                }

                if ((span).Length() < Radius + sc.Radius)
                {                                                                               //Create a vector from the difference of the two spheres' positions.
                    normal = Vector3.Normalize((span));                                         //If it is less than the sum of the radii, we've collided.
                    return true;                                                                //We get the normal vector of the collision point. Remember: The first operand
                }                                                                                      //second operand. The normal vector is saved with the 'out' keyword and we return true
            }
            return base.Collides(collider, out normal);
        }

        public override float? Intersects(Ray ray)
        {
            ray = toObject(ray);
            //Console.Write("Calling Sphere");
            BoundingSphere sphere = new BoundingSphere(Vector3.Zero, Radius); 
            float? t = sphere.Intersects(ray);
            return t;
        }
    }
}
